﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Drawing;
using Intorise.Common;

namespace Model
{
    public partial class Player
    {
        Timer tradeTimer = null;
        ManualResetEvent tradeEvent = new ManualResetEvent(true);

        //交易
        private void StartTradeTimer()
        {
            if (tradeTimer == null)
            {
                tradeTimer = new Timer(TradeMethod, null, 0, 1000 * 60 * 30);//30分钟进行一次交易
            }
        }

        private void TradeMethod(object obj)
        {
            lock (queue)
            {
                if (queue.Count > 0)
                {
                    ConsoleBLL.WriteLineWaring(string.Format("有{0}个角色需要交易，开始执行交易程序..", queue.Count));
                }
                else
                {
                    return;
                }
            }

            if (!gameEntered) { return; }
            AutoFight = false;
            while (this.Status == PlayerStatusEnum.自动打怪)
            {
                Thread.Sleep(1000);
            }
            this.Status = PlayerStatusEnum.交易物品;

            while (true)
            {
                Player tradePlayer = null;
                lock (queue)
                {
                    if (queue.Count > 0)
                    {
                        tradePlayer = queue[0];
                        queue.RemoveAt(0);
                    }
                    else
                    {
                        break;
                    }
                }
                if (tradePlayer != null)
                {
                    #region 交易
                    ConsoleBLL.WriteLineInfo(string.Format("前往{0}所在地进行交易...", tradePlayer));
                    if (this.Line != tradePlayer.Line)//线不同则换线
                    {
                        Change(tradePlayer.Line);
                    }
                    if (this.CurrentMap.ID != tradePlayer.CurrentMap.ID)//地图不同则传送
                    {
                        Transmit(tradePlayer.CurrentMap);
                    }
                    if (GameHelper.GetDistance(this.Location, tradePlayer.Location) > 6)
                    {
                        foreach (Point p in tradePlayer.FightMapLocation.LocationPoints)
                        {
                            int count = 1;
                            while (count < 4)
                            {
                                if (GoTo(p))
                                {
                                    break;
                                }
                                Thread.Sleep(1000);
                                ConsoleBLL.WriteLineError(string.Format("移动到{0}失败，重试第{1}次！", p, count));
                                count++;
                            }
                            if (count == 4)
                            {
                                ConsoleBLL.WriteLineError(string.Format("移动到{0}失败，交易取消！", tradePlayer, count)); return;
                            }
                        }
                    }

                    //发送交易邀请
                  //  InviteTrade(tradePlayer.ID);
                    //等待对方同意(60秒超时)
                    if (!tradeEvent.WaitOne(1000 * 60))
                    {
                        ConsoleBLL.WriteLineError(string.Format("等待{0}同意交易超时，交易取消！", tradePlayer)); return;
                    }

                    //等待对方放入物品并锁定(3分钟超时)
                    tradeEvent.Reset();
                    if (!tradeEvent.WaitOne(1000 * 60 * 3))
                    {
                        ConsoleBLL.WriteLineError(string.Format("等待{0}锁定交易超时，交易取消！", tradePlayer)); return;
                    }
                    LockTrade();//发送锁定

                    //等待对方确认交易(60秒超时)
                    tradeEvent.Reset();
                    if (!tradeEvent.WaitOne(1000 * 60))
                    {
                        ConsoleBLL.WriteLineError(string.Format("等待{0}确认交易超时，交易取消！", tradePlayer)); return;
                    }
                    AffirmTrade();//发送确认
                    ConsoleBLL.WriteLineInfo(string.Format("和挂机号{0}的交易已完成", tradePlayer));
                    #endregion
                }
            }

            ConsoleBLL.WriteLineInfo("交易程序执行完毕，继续挂机...");
            GameHelper.RunThread(() =>
            {
                AutoFight = true;
                if (GoFightLocation())
                {
                    StartAutoFight();
                }
            });
        }

        /// <summary>
        /// 邀请编号为id的玩家交易
        /// </summary>
        /// <param name="id"></param>
        private void InviteTrade(long id)
        {
            var data = Tools.Contact(new byte[] { 0x00, 0x01, 0xDD, 0x59 }, net.GetNetworkBytes(id), this.Version);
            data = Tools.Contact(net.GetNetworkBytes(data.Length), data);
            engine.SendData(data);
        }

        /// <summary>
        /// 同意交易邀请
        /// </summary>
        /// <param name="id"></param>
        private void AgreeTrade()
        {
            var data = Tools.Contact(new byte[] { 0x00, 0x01, 0xDD, 0x5A }, net.GetNetworkBytes(this.ID), this.Version);
            data = Tools.Contact(net.GetNetworkBytes(data.Length), data);
            engine.SendData(data);
        }

        /// <summary>
        /// 摆放物品
        /// </summary>
        /// <param name="item">物品</param>
        /// <param name="index">位置</param>
        private void PutItem(Thing item, int index)
        {
            var data = Tools.Contact(new byte[] { 0x00, 0x01, 0xDD, 0x5D }, net.GetNetworkBytes(index), net.GetNetworkBytes(item.InstanceID), this.Version);
            data = Tools.Contact(net.GetNetworkBytes(data.Length), data);
            engine.SendData(data);
        }

        /// <summary>
        /// 锁定交易
        /// </summary>
        private void LockTrade()
        {
            engine.SendData(new byte[] { 0x00, 0x00, 0x00, 0x06, 0x00, 0x01, 0xDD, 0x61, 0x01, 0x01 });
        }

        /// <summary>
        /// 确认交易
        /// </summary>
        private void AffirmTrade()
        {
            engine.SendData(new byte[] { 0x00, 0x00, 0x00, 0x06, 0x00, 0x01, 0xDD, 0x61, 0x02, 0x01 });
        }

        #region 交易处理器

        /// <summary>
        /// 交易邀请处理器
        /// </summary>
        /// <param name="x"></param>
        /// <returns></returns>
        private bool ProcessInviteTrade(Message x)
        {
            GameHelper.Run(x, r =>
            {
                var item = new InviteTradeMsg(x.Data);
                //if (item.InvitePlayerID != Player.Master.ID)//不是指定玩家则返回
                //{
                //    return;
                //}
                ConsoleBLL.WriteLine(string.Format("收到{0}的交易邀请，同意...", Player.Master));
                AgreeTrade();
                Thread.Sleep(1000);
                //放入交易物品
                for (int i = 0; i < Items.Count && i < 6; i++)
                {
                    PutItem(Items[i], i);
                    Thread.Sleep(10);
                }
                ConsoleBLL.WriteLine(string.Format("挂机号{0}已放置物品并锁定交易", this));
                LockTrade();//发送锁定交易
                //this.engine.SendData(DataPackager.GetAddPointData());
            });
            return true;
        }

        /// <summary>
        /// 同意交易处理器
        /// </summary>
        /// <param name="x"></param>
        /// <returns></returns>
        private bool ProcessAgreeTrade(Message x)
        {
            GameHelper.Run(x, r =>
            {
                var item = new AgreeTradeMsg(x.Data);
                ConsoleBLL.WriteLine("挂机号已同意交易");
                tradeEvent.Set();
               // this.Exp += 1;
            });
            return true;
        }

        /// <summary>
        /// 锁定交易处理器
        /// </summary>
        /// <param name="x"></param>
        /// <returns></returns>
        //private bool ProcessLockTrade(Message x)
        //{
        //    GameHelper.Run(x, r =>
        //    {
        //        var item = new LockTradeMsg(x.Data);
        //        if (item.Data.Last() == 2)//确认交易
        //        {
        //            ProcessAffirmTrade(x);
        //        }
        //        else
        //        {
        //            if (this.ID == Player.Master.ID)//当前号是仓库号，收到挂机号锁定交易
        //            {
        //                ConsoleBLL.WriteLine(string.Format("收到挂机号{0}已锁定交易", item.InvitePlayerID));
        //                tradeEvent.Set();
        //            }
        //            else//当前号是挂机号，收到仓库号锁定交易
        //            {
        //                ConsoleBLL.WriteLine(string.Format("收到仓库号{0}已锁定交易", Player.Master));
        //                AffirmTrade();
        //            }
        //        }
        //    });
        //    return true;
        //}

        /// <summary>
        /// 确认交易处理器
        /// </summary>
        /// <param name="x"></param>
        /// <returns></returns>
        //private bool ProcessAffirmTrade(Message x)
        //{
        //    GameHelper.Run(x, r =>
        //    {
        //        var item = new AffirmTradeMsg(x.Data);
        //        if (this.ID == Player.Master.ID)//当前号是仓库号，收到挂机号确认交易
        //        {
        //            ConsoleBLL.WriteLine(string.Format("收到挂机号{0}已确认交易", item.InvitePlayerID));
        //            tradeEvent.Set();
        //        }
        //        else//当前号是挂机号，收到仓库号确认交易
        //        {
        //            ConsoleBLL.WriteLine(string.Format("收到仓库号{0}已确认交易，交易已完成", Player.Master));
        //        }
        //    });
        //    return true;
        //}
        #endregion
    }
}
